package com.lagou.edu.filter;

import com.lagou.edu.feign.UserServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private UserServiceFeign userServiceFeign;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();


        //请求路径
        String path = request.getPath().toString();
        // ⽤用户微服务和验证码微服务的请求不过滤
        if(path.indexOf("/api/user") != -1 || path.indexOf("/api/code") != -1){
            return chain.filter(exchange);
        }
        //从cookie中拿到token
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie token = cookies.getFirst("token");
//        List<String> tokens = request.getHeaders().get("token");

        //验证token是否存在,没有token则拦截不让调用
        if(cookies == null || cookies.isEmpty() ){
            System.out.println("未检测到token");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        //token不为空，验证token是否有效
        String emailByToken = userServiceFeign.info(token.getValue());
        if(emailByToken != null){
            //有效，放行
            return chain.filter(exchange);
        }else{
            System.out.println("未检测到token");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
